﻿using RTW.Core.Datas;
using RTW.Core.Ioc;
using RTW.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace RTW.Servers
{
    public class TMenuServer : BaseDAL<TMenu>, IAutoInject
    {
        //获取个人的菜单树
        public List<TMenu> GetMenuTreeByUser(string UserID)
        {
            // return //DbType.DB().Select<TMenu, TUserInfo>().InnerJoin((a, b) => a.Bak1.Contains(b.RoleID) && a.DMID == b.DMID).Where((a, b) => b.Id == UserID&&a.IsDelete=="0").OrderBy((a,b)=>a.Flag1).ToList<TMenu>();
            return DbType.DB().Select<TMenu>().Where(a => DbType.DB().Select<TUserInfo>().Where(b => b.ID == UserID).First(b => a.Bak1.Contains(b.RoleID) && a.IsDelete == "0")).OrderBy(a => a.Flag1).ToTreeList<TMenu>();
        }

        //无限递归获取菜单树
        public List<TMenu> GetMenuTreeCte()
        {
            var list = DbType.DB().Select<TMenu>().Where(a => a.Parent_ID == null).AsTreeCte().OrderByDescending(a => a.Flag1).ToTreeList<TMenu>();
            return list;
        }

        //逻辑删除
        public async Task<bool> LogicalDelete(string ID)
        {
            var result = DbType.DB().Update<TMenu>().Set(a => a.IsDelete, "1").Where(m => m.ID == ID).ExecuteAffrowsAsync();
            return await result > 0;
        }

        //返回列表查询
        public async Task<object> GetMenuForJson(string DMID)
        {
            // var result = DbType.DB().Update<TMenu>().Set(a => a.IsDelete, "1").Where(m => m.ID == ID).ExecuteAffrows();
            //设置查询条件
            var list = DbType.DB().Queryable<TMenu>()

                .Where(m => m.IsDelete != "1")
                .WhereIf(DMID != null, m => m.DMID == DMID)
                .ToListAsync((b) => new
                {
                   b.ID,
                   b.ImgPath,
                   b.MenuName,
                   b.PageUrl,
                   b.Bak1,
                   b.Bak2,
                   b.Flag1,                  
                   Roles = string.Join(",", DbType.DB().Select<TRole>().Where(c=>b.Bak1.Contains(c.ID)).ToList(c => c.RName))//拼接有权限的角色名
                });
            return await list;
        }
     
    }
}